#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
目标连接器 - 针对 101.37.80.173:8888 的优化连接工具
基于成功连接经验优化的连接策略
"""

import socket
import time
import threading
import subprocess
import sys
import json
import os
from datetime import datetime
import random

# 导入安全属性访问器
try:
    from core.safe_attribute_accessor import safe_getattr, safe_hasattr
except ImportError:
    # 如果导入失败，提供简单的备用实现
    def safe_getattr(obj, attr, default=None):
        return getattr(obj, attr, default)
    
    def safe_hasattr(obj, attr):
        return hasattr(obj, attr)

class TargetConnector:
    """针对特定目标的优化连接器"""
    
    def __init__(self, target_ip="101.37.80.173", target_port=8888):
        self.target_ip = target_ip
        self.target_port = target_port
        self.connection_attempts = 0
        self.successful_connections = 0
        self.active_connections = []
        self.running = False
        self.session_log = []
        
    def log(self, message, level="INFO"):
        """增强的日志记录"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        log_entry = f"[{timestamp}] {level}: {message}"
        print(log_entry)
        self.session_log.append({
            "timestamp": timestamp,
            "level": level,
            "message": message
        })
        
    def test_connectivity(self):
        """测试基础连通性"""
        self.log(f"Testing connectivity to {self.target_ip}:{self.target_port}")
        
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(5)
            
            start_time = time.time()
            result = sock.connect_ex((self.target_ip, self.target_port))
            end_time = time.time()
            
            sock.close()
            
            if result == 0:
                response_time = (end_time - start_time) * 1000
                self.log(f"✓ Connection successful! Response time: {response_time:.2f}ms", "SUCCESS")
                return True, response_time
            else:
                self.log(f"✗ Connection failed with error code: {result}", "ERROR")
                return False, None
                
        except Exception as e:
            self.log(f"✗ Connection test failed: {str(e)}", "ERROR")
            return False, None
    
    def establish_connection(self, timeout=10):
        """建立连接"""
        try:
            self.log(f"Establishing connection to {self.target_ip}:{self.target_port}")
            
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(timeout)
            
            # 连接到目标
            sock.connect((self.target_ip, self.target_port))
            
            self.successful_connections += 1
            self.log("✓ Connection established successfully!", "SUCCESS")
            
            return sock
            
        except socket.timeout:
            self.log("✗ Connection timeout", "ERROR")
            return None
        except ConnectionRefusedError:
            self.log("✗ Connection refused by target", "ERROR")
            return None
        except Exception as e:
            self.log(f"✗ Connection failed: {str(e)}", "ERROR")
            return None
    
    def send_command(self, sock, command):
        """发送命令到目标"""
        try:
            if sock:
                command_with_newline = command + "\n"
                sock.send(command_with_newline.encode())
                self.log(f"Command sent: {command}", "INFO")
                
                # 接收响应
                response = sock.recv(4096).decode('utf-8', errors='ignore')
                self.log(f"Response received: {response.strip()}", "INFO")
                return response
            else:
                self.log("No active connection to send command", "ERROR")
                return None
                
        except Exception as e:
            self.log(f"Failed to send command: {str(e)}", "ERROR")
            return None
    
    def interactive_session(self, sock):
        """交互式会话"""
        self.log("Starting interactive session (type 'exit' to quit)")
        
        try:
            while True:
                command = input("$ ")
                
                if command.lower() in ['exit', 'quit']:
                    break
                
                if command.strip():
                    response = self.send_command(sock, command)
                    if response:
                        print(response)
                        
        except KeyboardInterrupt:
            self.log("Interactive session interrupted by user", "INFO")
        except Exception as e:
            self.log(f"Interactive session error: {str(e)}", "ERROR")
    
    def automated_test_sequence(self, sock):
        """自动化测试序列"""
        test_commands = [
            "whoami",
            "pwd", 
            "uname -a",
            "id",
            "ps aux | head -5"
        ]
        
        self.log("Running automated test sequence")
        results = {}
        
        for cmd in test_commands:
            self.log(f"Executing: {cmd}")
            response = self.send_command(sock, cmd)
            results[cmd] = response
            time.sleep(1)  # 短暂延迟
            
        return results
    
    def connection_stability_test(self, duration=60):
        """连接稳定性测试"""
        self.log(f"Starting {duration}s connection stability test")
        
        start_time = time.time()
        test_results = []
        
        while time.time() - start_time < duration:
            success, response_time = self.test_connectivity()
            test_results.append({
                "timestamp": time.time(),
                "success": success,
                "response_time": response_time
            })
            
            time.sleep(5)  # 每5秒测试一次
        
        # 分析结果
        successful_tests = sum(1 for r in test_results if r["success"])
        success_rate = (successful_tests / len(test_results)) * 100
        
        avg_response_time = None
        if successful_tests > 0:
            response_times = [r["response_time"] for r in test_results if r["response_time"]]
            avg_response_time = sum(response_times) / len(response_times)
        
        self.log(f"Stability test completed: {success_rate:.1f}% success rate", "INFO")
        if avg_response_time:
            self.log(f"Average response time: {avg_response_time:.2f}ms", "INFO")
            
        return {
            "success_rate": success_rate,
            "avg_response_time": avg_response_time,
            "total_tests": len(test_results),
            "successful_tests": successful_tests
        }
    
    def generate_report(self):
        """生成连接报告"""
        report = {
            "target": f"{self.target_ip}:{self.target_port}",
            "timestamp": datetime.now().isoformat(),
            "connection_attempts": self.connection_attempts,
            "successful_connections": self.successful_connections,
            "session_log": self.session_log
        }
        
        report_file = f"target_connection_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        
        try:
            with open(report_file, 'w', encoding='utf-8') as f:
                json.dump(report, f, indent=2, ensure_ascii=False)
            
            self.log(f"Report saved to: {report_file}", "INFO")
            return report_file
            
        except Exception as e:
            self.log(f"Failed to save report: {str(e)}", "ERROR")
            return None
    
    def run_comprehensive_test(self):
        """运行综合测试"""
        self.log("=== Starting Comprehensive Connection Test ===")
        
        # 1. 基础连通性测试
        self.log("Phase 1: Basic connectivity test")
        success, response_time = self.test_connectivity()
        
        if not success:
            self.log("Basic connectivity failed. Aborting test.", "ERROR")
            return False
        
        # 2. 建立连接
        self.log("Phase 2: Establishing connection")
        sock = self.establish_connection()
        
        if not sock:
            self.log("Failed to establish connection. Aborting test.", "ERROR")
            return False
        
        try:
            # 3. 自动化测试
            self.log("Phase 3: Automated command testing")
            test_results = self.automated_test_sequence(sock)
            
            # 4. 稳定性测试
            sock.close()  # 关闭当前连接进行稳定性测试
            self.log("Phase 4: Connection stability test")
            stability_results = self.connection_stability_test(30)  # 30秒测试
            
            # 5. 生成报告
            self.log("Phase 5: Generating report")
            report_file = self.generate_report()
            
            self.log("=== Comprehensive Test Completed Successfully ===", "SUCCESS")
            return True
            
        except Exception as e:
            self.log(f"Test failed: {str(e)}", "ERROR")
            return False
        finally:
            if sock:
                sock.close()

def main():
    """主函数"""
    print("Target Connector - 101.37.80.173:8888 Connection Tool")
    print("=" * 50)
    
    connector = TargetConnector()
    
    if len(sys.argv) > 1:
        mode = sys.argv[1].lower()
        
        if mode == "test":
            # 运行综合测试
            connector.run_comprehensive_test()
            
        elif mode == "connect":
            # 建立交互式连接
            sock = connector.establish_connection()
            if sock:
                try:
                    connector.interactive_session(sock)
                finally:
                    sock.close()
                    
        elif mode == "stability":
            # 运行稳定性测试
            duration = int(sys.argv[2]) if len(sys.argv) > 2 else 60
            connector.connection_stability_test(duration)
            
        else:
            print("Usage: python target_connector.py [test|connect|stability] [duration]")
            
    else:
        # 默认运行综合测试
        connector.run_comprehensive_test()

if __name__ == "__main__":
    main()